package com.application.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.MyWXPayConfig;
import com.github.wxpay.sdk.SignKit;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.platform.annotation.Controller;
import com.platform.interceptor.AuthInterceptor;
import com.platform.interceptor.LoginInterceptor;
import com.platform.interceptor.ParamPkgInterceptor;
import com.platform.mvc.base.BaseController;
import com.platform.tools.ToolCache;

import java.text.MessageFormat;
import java.util.Map;

@Controller("/api/wx")
@Clear({LoginInterceptor.class, AuthInterceptor.class, ParamPkgInterceptor.class})
public class WxApiController extends BaseController {

    public final String AccessToken_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    public final String Ticket_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
    private static final Log log = Log.getLog(WxApiController.class);

    private static MyWXPayConfig config = null;

    static {
        try {
            config = MyWXPayConfig.getInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * url：当前页面地址，不包含#及后内容
     *
     * @throws Exception
     */
    public void config() throws Exception {
        String appid = config.getAppID();
        String secret = config.getAppSecret();
        String url = getPara("url");
        String cacheKey = "jsapi_ticket_"  + getCUserIds() + url;

        Map<String, String> map;

        Object ticket1 = ToolCache.get(cacheKey);
        if(ticket1 != null) {
            map = ToolCache.get(cacheKey);
        } else {
            String accessToken = HttpKit.get(AccessToken_URL.replace("APPID", appid).replace("APPSECRET", secret));
            log.info("getMessage accessToken:" + accessToken);
            JSONObject jsonObject = JSON.parseObject(accessToken);
            if (jsonObject.containsKey("errcode")) {
                error(400, jsonObject.getString("errmsg"));
                return;
            }
            String ticketStr = HttpKit.get(Ticket_URL.replace("ACCESS_TOKEN", jsonObject.getString("access_token")));
            log.info("getMessage js-ticketStr:" + ticketStr);
            JSONObject json = JSON.parseObject(ticketStr);
            if(json.getInteger("errcode") != 0) {
                error(400, json.getString("errmsg"));
                return;
            }
            map = SignKit.sign(json.getString("ticket"), url);
            ToolCache.set(cacheKey, 7000, map);
        }
        map.put("appId", config.getAppID());
        success(map);

        log.info(MessageFormat.format("appID: {0}, secret: {1}, url: {2}", appid, secret, url));
        log.info(JSON.toJSONString(map));
    }


    /*
    获取用户微信登陆的用户信息，头像昵称等，用于实现微信登陆
     */
    public void getUserInfo() {
        String code = getPara("code");
        if(StrKit.isBlank(code)) {
            error(400, "code参数错误");
            return;
        }
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
        String res = HttpKit.get(MessageFormat.format(tokenUrl, config.getAppID(), config.getAppSecret(), code));

        log.info("############" +MessageFormat.format(tokenUrl, config.getAppID(), config.getAppSecret(), code));
        log.info("############" +res);

        JSONObject json = JSON.parseObject(res);
        /* let json = {"access_token":"42_RCkoulg58HVh5b1pVftqsTycoqWXnSzK2xJb_PI3nIyuxYa77EovZfaDC-G-vtgpfoOcQ_j_1JhmISTZ1Inzj8zNxEitAnzxOl-o1_pAJFc","expires_in":7200,"refresh_token":"42_rQmdIifsToRVWyPcIb23HsYoZJ2fpBJTBx9BSaIATcDDTz9ijmq252FfRI-oM1hLUg-g2-PKNvepIA39wbOliH9MVeZeDd6mKinA0oepsM0","openid":"oxbwj6ldeiRjN56d1roM7w7yelGo","scope":"snsapi_userinfo"}
 */
        if(!json.containsKey("access_token")) {
            error(400, "获取用户信息失败");
            return;
        }

        String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
        res = HttpKit.get(MessageFormat.format(getUserInfoUrl, json.getString("access_token"), json.getString("openid")));

        log.info("############" + MessageFormat.format(getUserInfoUrl, json.getString("access_token"), json.getString("openid")));
        log.info("############" + res);

        JSONObject obj = JSON.parseObject(res);

        success(obj);
    }
}
